<script setup>
import {ref} from 'vue';
import {showToast} from 'vant';
import {useRouter} from "vue-router";

/**
 * 搜索过滤
 * @type {Ref<UnwrapRef<string>, UnwrapRef<string> | string>}
 */
const searchText = ref('');
const onSearch = (value)=>{
  tagList.value =originTagList.map(parentTag=>{
    const tempChildren=[...parentTag.children];// 创建父标签的子标签数组的副本
    const temParenTag={...parentTag};// 创建父标签对象的副本
    temParenTag.children=tempChildren.filter(item=>
        item.text.includes(searchText.value))// 过滤子标签，只保留文本中包含 `searchText.value` 的标签
    return temParenTag;// 返回修改后的父标签
  });
}
const onCancel = () =>{
  searchText.value= "";
  tagList.value=originTagList;
}

//已选择的标签
const activeIds = ref([]);
const activeIndex = ref(0);

const originTagList=[{
      text: '性别',
      children: [
        {text: '男', id: '男'},
        {text: '女', id: '女'},
      ],
    },
    {
      text: '年级',
      children: [
        {text: '大一', id: '大一'},
        {text: '大二', id: '大二'},
        {text: '大三', id: '大三'},
      ],
    },]

//标签列表
let tagList =ref(originTagList);


//移除标签
const doClose = (tag) => {
  activeIds.value = activeIds.value.filter(item => {
    return item !== tag;
  })
}
const router=useRouter()
const doSearchResult=()=>{
  router.push({
    path:'/user/list',
    query:{
      tag:activeIds.value
    }
  })
}
</script>

<template>
  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入要搜索的标签"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>
  <van-divider content-position="left">已选标签</van-divider>
  <div v-if="activeIds.length===0">请选择标签</div>
  <van-row gutter="16" style="padding-left: 16px">
    <van-col  v-for="tag in activeIds">
      <van-tag closeable size="small" type="primary" @close="doClose(tag)">
        {{ tag }}
      </van-tag>
    </van-col>
  </van-row>


  <van-divider content-position="left">选择标签</van-divider>
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />
  <div style="padding: 12px">
  <van-button block type="primary" @click="doSearchResult">搜索</van-button>
  </div>
</template>

<style scoped>

</style>